package com.sduept.nwld.wave.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.core.dao.SuperDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 相量数据REST服务
 * @author Ningfw
 * @date 2017-06-20
 *
 */
@RestController
@RequestMapping("/harmonic/")
public class HarmonicServices {

	@Autowired
	private SuperDAO superDao;
	
	/**
	 * 相量
	 * @param fileId
	 * @param lineId
	 * @param harRank
	 * @param eleType
	 * @return
	 */

	@GetMapping("/getHarmonic/{fileId}/{lineId}")
	public String getHarmonic(@PathVariable("fileId") String fileId,@PathVariable("lineId") String lineId){

		JSONObject jso = new JSONObject();
		
		StringBuffer sqlSb = new StringBuffer();//查询全部相量sql语句中的字段
		StringBuffer xaxisSb = new StringBuffer();//查询全部相量sql列简化后的名，作为x轴
		//故障前*ms值、故障前*ms相角
		StringBuffer preFaultStr = new StringBuffer();//故障前*ms值/相角
		StringBuffer xPreValue = new StringBuffer();//故障前*ms值/相角的x轴
		for(int i = 60; i >= 20; i = i-5){
			preFaultStr.append(","+("pre_fault_value_"+i)).append(","+("pre_fault_phase_"+i));
			xPreValue.append(",-"+i+"ms");
		}
		//故障后*ms值、故障后*ms相角
		StringBuffer postFaultStr = new StringBuffer();//故障后*ms值
		StringBuffer xPostValue = new StringBuffer();//故障后*ms值/相角的x轴
		for(int i = 0; i <= 180; i = i+5){
			postFaultStr.append(","+("post_fault_value_"+i)).append(","+("post_fault_phase_"+i));
			xPostValue.append(","+i+"ms");
		}
		//重合闸后*ms值、重合闸后*ms相角
		StringBuffer reclosingValueStr = new StringBuffer();//重合闸后*ms值
		StringBuffer xRecloseValue = new StringBuffer();//故障后*ms值/相角的x轴
		for(int i = 0; i <= 180; i = i+5){
			reclosingValueStr.append(","+("reclosing_value_"+i)).append(","+("reclosing_phase_"+i));
			xRecloseValue.append(",+"+i+"ms");
		}
		sqlSb.append("electrical_type,phase_type").append(preFaultStr).append(postFaultStr).append(reclosingValueStr);
		xaxisSb.append(xPreValue.substring(1)).append(xPostValue).append(xRecloseValue);
		String[] xArr = xaxisSb.toString().split(",");//x轴
		
		String sqlHar = "SELECT "+sqlSb+" FROM t_lbtz_line_harmonic lh WHERE lh.fault_file_id = '"+fileId+"' AND "
			+ "lh.line_id = '"+lineId+"' AND lh.harmonic_rank = '1'";
		List<?> listHar = superDao.nativeQuery(sqlHar);
		List<String> valueList = null;//波形y轴（数据库中的*ms值）
		List<String> phaseList = null;//圆角图Y轴（数据库中的*ms相角）
		for(Object obj : listHar){
			valueList = new ArrayList<String>();
			phaseList = new ArrayList<String>();
			Object[] objArr = (Object[])obj;
			Object[] objType = Arrays.copyOf(objArr, 2);//电气类型、相别
			Object[] objs = Arrays.copyOfRange(objArr, 2, objArr.length);//数据
			for(int i=0; i<objs.length; i++){
				if(i % 2 == 0){//偶数为波形y值
//					valueList.add(objs[i].toString());
					valueList.add(keepBit(objs[i].toString()));
				}else{//奇数为圆角图y值
//					phaseList.add(objs[i].toString());
					phaseList.add(keepBit(objs[i].toString()));
				}
			}

			JSONObject keyValueJso = new JSONObject();//存放每一条数据的x轴和*ms相角的键值对
			for(int i = 0; i < phaseList.size(); i++){
				keyValueJso.put(xArr[i], phaseList.get(i));
			}
			
			JSONObject harmonObj = new JSONObject();//存放每一条数据的*ms和*ms相角的键值对
			harmonObj.put("value", valueList);
			harmonObj.put("phase", keyValueJso);
			
			String harmonic;//键
			if("1".equals(objType[0].toString())){//1：电压
				harmonic = "U"+objType[1].toString().toLowerCase();
			}else{//电流
				harmonic = "I"+objType[1].toString().toLowerCase();
			}
			
			jso.put(harmonic, harmonObj);//6条波，每一条波中都有*ms值和 x轴与*ms相角的键值对
		}
		
		
		jso.put("xAxis", xArr);//x轴
		return jso.toJSONString();
	}
	
	/**
	 * 谐波
	 * @param fileId
	 * @param lineId
	 * @param harRank
	 * @return
	 */

	@GetMapping("/getLineHarmonic/{fileId}/{lineId}")
	public String getLineHarmonic(@PathVariable("fileId") String fileId,@PathVariable("lineId") String lineId){

		JSONObject jso = new JSONObject();
		
		StringBuffer sqlSb = new StringBuffer();//查询全部谐波sql语句中的字段
		StringBuffer xaxisSb = new StringBuffer();//查询全部谐波sql列简化后的名，作为x轴
		//故障前*ms值
		StringBuffer preFaultStr = new StringBuffer();//故障前*ms值
		StringBuffer xPreValue = new StringBuffer();//故障前*ms值的x轴
		for(int i = 60; i >= 20; i = i-5){
			preFaultStr.append(","+("pre_fault_value_"+i));
			xPreValue.append(",-"+i+"ms");
		}
		//故障后*ms值
		StringBuffer postFaultStr = new StringBuffer();//故障后*ms值
		StringBuffer xPostValue = new StringBuffer();//故障后*ms值的x轴
		for(int i = 0; i <= 180; i = i+5){
			postFaultStr.append(","+("post_fault_value_"+i));
			xPostValue.append(","+i+"ms");
		}
		//重合闸后*ms值
		StringBuffer reclosingValueStr = new StringBuffer();//重合闸后*ms值
		StringBuffer xRecloseValue = new StringBuffer();//故障后*ms值的x轴
		for(int i = 0; i <= 180; i = i+5){
			reclosingValueStr.append(","+("reclosing_value_"+i));
			xRecloseValue.append(",+"+i+"ms");
		}
		sqlSb.append(preFaultStr.substring(1)).append(postFaultStr).append(reclosingValueStr).append(",electrical_type").append(",phase_type");
		xaxisSb.append(xPreValue).append(xPostValue).append(xRecloseValue);
		String[] xArr = xaxisSb.toString().split(",");//x轴
		
		String sqlHar = "SELECT "+sqlSb+" FROM t_lbtz_line_harmonic lh WHERE lh.fault_file_id = '"+fileId+"' AND "
				+ "lh.line_id = '"+lineId+"'";
		List<?> listHar = superDao.nativeQuery(sqlHar);
		
		JSONArray js1A = new JSONArray();//1A
		List<JSONObject> list1A = new ArrayList<JSONObject>();
		JSONArray js2A = new JSONArray();//2A
		List<JSONObject> list2A = new ArrayList<JSONObject>();
		JSONArray js1B = new JSONArray();//1B
		List<JSONObject> list1B = new ArrayList<JSONObject>();
		JSONArray js2B = new JSONArray();//2B
		List<JSONObject> list2B = new ArrayList<JSONObject>();
		JSONArray js1C = new JSONArray();//1C
		List<JSONObject> list1C = new ArrayList<JSONObject>();
		JSONArray js2C = new JSONArray();//2C
		List<JSONObject> list2C = new ArrayList<JSONObject>();
		
		for(Object obj : listHar){//按电气类型+类别分组
			Object[] objs = (Object[])obj;
			String elePhase = ""+objs[objs.length-2]+""+objs[objs.length-1]+"";//电气类型+相别
			
			objs = Arrays.copyOf(objs, (objs.length-2));//截去电气类型和相别
			for(int i=0; i < objs.length; i++){//保留三位小数
				objs[i] = keepBitDb(objs[i].toString());
			}
			
			if("1A".equals(elePhase)){
				js1A.add(objs);
			}else if("2A".equals(elePhase)){
				js2A.add(objs);
			}else if("1B".equals(elePhase)){
				js1B.add(objs);
			}else if("2B".equals(elePhase)){
				js2B.add(objs);
			}else if("1C".equals(elePhase)){
				js1C.add(objs);
			}else{
				js2C.add(objs);
			}
		}
		
		for(int i=0; i < js1A.size(); i++){//1A的键值对
			JSONObject jso1A = new JSONObject();
			if(0 == i){//第一个叫基波
				jso1A.put("frequency", "基波");
				jso1A.put("data", js1A.get(i));
			}else{
				jso1A.put("frequency", (i+1)+"次");
				jso1A.put("data", js1A.get(i));
			}
			list1A.add(jso1A);
		}
		for(int i=0; i < js2A.size(); i++){//2A的键值对
			JSONObject jso2A = new JSONObject();
			if(0 == i){//第一个叫基波
				jso2A.put("frequency", "基波");
				jso2A.put("data", js2A.get(i));
			}else{
				jso2A.put("frequency", (i+1)+"次");
				jso2A.put("data", js2A.get(i));
			}
			list2A.add(jso2A);
		}
		for(int i=0; i < js1B.size(); i++){//1B的键值对
			JSONObject jso1B = new JSONObject();
			if(0 == i){//第一个叫基波
				jso1B.put("frequency", "基波");
				jso1B.put("data", js1B.get(i));
			}else{
				jso1B.put("frequency", (i+1)+"次");
				jso1B.put("data", js1B.get(i));
			}
			list1B.add(jso1B);
		}
		for(int i=0; i < js2B.size(); i++){//2B的键值对
			JSONObject jso2B = new JSONObject();
			if(0 == i){//第一个叫基波
				jso2B.put("frequency", "基波");
				jso2B.put("data", js2B.get(i));
			}else{
				jso2B.put("frequency", (i+1)+"次");
				jso2B.put("data", js2B.get(i));
			}
			list2B.add(jso2B);
		}
		for(int i=0; i < js1C.size(); i++){//1C的键值对
			JSONObject jso1C = new JSONObject();
			if(0 == i){//第一个叫基波
				jso1C.put("frequency", "基波");
				jso1C.put("data", js1C.get(i));
			}else{
				jso1C.put("frequency", (i+1)+"次");
				jso1C.put("data", js1C.get(i));
			}
			list1C.add(jso1C);
		}
		for(int i=0; i < js2C.size(); i++){//2C的键值对
			JSONObject jso2C = new JSONObject();
			if(0 == i){//第一个叫基波
				jso2C.put("frequency", "基波");
				jso2C.put("data", js2C.get(i));
			}else{
				jso2C.put("frequency", (i+1)+"次");
				jso2C.put("data", js2C.get(i));
			}
			list2C.add(jso2C);
		}
		
		JSONObject jsoEle = new JSONObject();
		jsoEle.put("phase1A", list1A);//1电压A相别
		jsoEle.put("phase1B", list1B);//1电压B相别
		jsoEle.put("phase1C", list1C);//1电压C相别
		jsoEle.put("phase2A", list2A);//2电流A相别
		jsoEle.put("phase2B", list2B);//2电流B相别
		jsoEle.put("phase2C", list2C);//2电流C相别
		jsoEle.put("millisecond", xArr);//x轴
		
		jso.put("data", jsoEle);
		return jso.toJSONString();
	}
	
	/**
	 * 保留三位小数
	 * @param str
	 * @return
	 */
	public String keepBit(String str){
		if(null != str && !"".equals(str)){
			BigDecimal bd = new BigDecimal(str);
			String res = bd.setScale(3, BigDecimal.ROUND_HALF_UP).toString();
			return res;
		}else{
			return null;
		}
	}
	
	/**
	 * 保留三位小数，返回Double
	 * @param str
	 * @return
	 */
	public Double keepBitDb(String str){
		if(null != str && !"".equals(str)){
			BigDecimal bd = new BigDecimal(str);
			Double res = bd.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
			return res;
		}
		return 0.0;
	}
	
}
